package com.well.menjin.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.well.menjin.dao.IDoorcontrDao;
import com.well.menjin.domain.Doorcontr;
import com.well.menjin.model.Sort;

@Repository
public class DoorcontrDaoImpl implements IDoorcontrDao {
	@Autowired
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Doorcontr> getDoorcontrs(int start,int limit,int page,List<Sort> sorto,String controller_id,
			String controller_name,String ip_address) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Doorcontr.class).
				setFirstResult(start).setMaxResults(limit);
		if (!StringUtils.isEmpty(controller_id)) {
			criteria.add(Restrictions.like("controller_id", "%"+controller_id+"%"));
		}
		if (!StringUtils.isEmpty(controller_name)) {
			criteria.add(Restrictions.like("controller_name","%"+controller_name+"%"));
		}
		if (!StringUtils.isEmpty(ip_address)) {
			criteria.add(Restrictions.like("ip_address", "%"+ip_address+"%"));
		}
		if(sorto!=null&&sorto.size()>0){
			for(Sort sort:sorto){
				if("asc".equalsIgnoreCase(sort.getDirection())){
					criteria.addOrder(Order.asc(sort.getProperty()));
				}else {
					criteria.addOrder(Order.desc(sort.getProperty()));
				}
			}
		}
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Doorcontr> getDoorcontrsCount(String controller_id, String controller_name, String ip_address) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Doorcontr.class);
		if (!StringUtils.isEmpty(controller_id)) {
			criteria.add(Restrictions.like("controller_id", "%"+controller_id+"%"));
		}
		if (!StringUtils.isEmpty(controller_name)) {
			criteria.add(Restrictions.like("controller_name","%"+controller_name+"%"));
		}
		if (!StringUtils.isEmpty(ip_address)) {
			criteria.add(Restrictions.like("ip_address", "%"+ip_address+"%"));
		}
		return criteria.list();
	}

	@Override
	public boolean isExist(String controller_id) {
		Doorcontr doorcontr = (Doorcontr) sessionFactory.getCurrentSession().
				createCriteria(Doorcontr.class).add(Restrictions.
						eq("controller_id", controller_id)).uniqueResult();
		if (null !=doorcontr) {
			return false;
		}else {
			return true;
		}
	}

	@Override
	public void addDoorcontr(Doorcontr doorcontr) {
		sessionFactory.getCurrentSession().save(doorcontr);
	}

	@Override
	public void updateDoorcontr(Doorcontr doorcontr) {
		sessionFactory.getCurrentSession().saveOrUpdate(doorcontr);	
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Doorcontr> getDoorcontrOpts() {
		return sessionFactory.getCurrentSession().createCriteria(Doorcontr.class).list();
	}
}
